<?php

	namespace App\Models\Import;

	use Illuminate\Database\Eloquent\Factories\HasFactory;
	use Illuminate\Database\Eloquent\Model;
    use App\Consts\TableConsts\TableConsts;

	class mapExcelFileColumnHeaderToDatabaseTableFieldModel extends Model
	{
		use HasFactory;

		# model default initialization
		#
		#
		protected   $table																								= TableConsts::CY_CREDIT_PROJECT_EX_TABLE_NAME	;
		protected   $primaryKey																							= 'id'											;
		public		$timestamps																							= false											;

		public function __construct	($p_controller=null)
		{	
			$this->m_cHelper																							= app()->gcHelper								;
			$this->m_p_controller																						= $p_controller									;
		}

		/* 映射 excel 文件列头到数据库表字段
		 *
		 *
		 *
		 *
		 */
		public function mapExcelFileColumnHeaderToDatabaseTableField ($j)
		{
			# map field md5 to field name
			#
			#
			$this->map_field_md5_2_field_name($j/* pass by reference */);

			# save it 
			#
			#
			#
			if( $this->m_cHelper->gfIsPureInteger($j->client_id) && $j->client_id >0 )
			{
				$this->m_cHelper->gfDbQuery()->updateByArrayWithWhere		
				(
					$this->m_cHelper->gfGetTableNameByConstKey('ME_CLIENT')
					,
					["where client_id=?",[$j->client_id]]
					,
					[
						# save => 标准的映射 excel 文件列头到数据库表字段
						# 新增一个字段
						#
                            'client_map_excel_file_column_header_to_database_table_field'	=> $this->m_cHelper->gfJsonEncode([
                            'map_excel_file_column_header_to_database_table_field'=> $j->map_excel_file_column_header_to_database_table_field,
                            'map_excel_file_column_header_to_database_table_field_custom'=> $j->map_excel_file_column_header_to_database_table_field_custom,
                        ])
						,
						# save => 自定义字段
						# 2023/7/10 禁止更新此次短
						#
//						'client_custom_json'											=> $this->m_cHelper->gfJsonEncode($j->custom_field)
					]
				);

				$r																		= 'ok';
				$ar																		= $this->get_client_custom_field ($j->client_id);
			}
			else
			{
				$r																		= 'error';
			}
			$ar['status']																= $r;

			return $ar ;

		}
		private function map_field_md5_2_field_name (&$j)
		{
			# cache field md5
			#
			#
			#
			$map_field_md5_2_field_name_ex = [];foreach($this->lawCaseTableFieldList(true/* enable field name */)['law_case_table_field_list'] as $one_field_md5)
			{
				$map_field_md5_2_field_name_ex[$one_field_md5['field_md5']]		= $one_field_md5['field'];
			}

			# begin map field md5 to field name
			#
			#
			#
			foreach($j->map_excel_file_column_header_to_database_table_field as $one_map)
			{
				# field md5														=> field name
				#
				#
				$one_map->field													= @$map_field_md5_2_field_name_ex[$one_map->key];				
			}
		}

		private function get_client_custom_field ($client_id)
		{
			$this->m_cHelper->gfDbQuery()->select ("select client_map_excel_file_column_header_to_database_table_field,client_custom_json from ".$this->m_cHelper->gfGetTableNameByConstKey('ME_CLIENT')." where client_id=?",[$client_id])->forEachRow 
			(
				function ($row)
				{
					return $row->getOneRowAllData();
				}
				,
				$arx
			);			
			
			# 这里开启 php 容错	$arx => 如果为空值可以正常被处理
			#
			#
			#
			$client_map_excel_file_column_header_to_database_table_field													=	[
																																	'map_excel_file_column_header_to_database_table_field'	=> []
																																	,
																																	'custom_field'											=> []
																																];
			@$this->m_cHelper->gfJsonDecode	(
												$arx['content'][0]['client_map_excel_file_column_header_to_database_table_field']
												,
												function(&$j) use(&$client_map_excel_file_column_header_to_database_table_field)
												{	
													# disable output field name to front end
													#
													#
													$arxx																	= $j->toArray();foreach($arxx['map_excel_file_column_header_to_database_table_field'] as &$one_map){unset($one_map['field']);}

													# save it
													#
													#
													$client_map_excel_file_column_header_to_database_table_field			= $arxx;
												}
											);
			@$this->m_cHelper->gfJsonDecode	(
												$arx['content'][0]['client_custom_json']
												,
												function(&$j) use(&$client_map_excel_file_column_header_to_database_table_field)
												{
													$client_map_excel_file_column_header_to_database_table_field ['custom_field']	= $j->toArray();	
												}
											);
			#
			#
			#			
			return $client_map_excel_file_column_header_to_database_table_field;
		}

		/*  获取 excel 文件列头与数据库字段之间的映射关系
		 *
		 *
		 *
		 *
		 *
		 *
		 */
		public function getMapRelationBetweenExcelFileColumnHeaderAndDatabaseField ($j)
		{
			$ar									= $this->get_client_custom_field($j->client_id)											;	# excel 和 数据库字段映射关系
			$ar['law_case_table_field_list']	= $this->m_cHelper->toObject($this->lawCaseTableFieldList())->law_case_table_field_list	;	# 法律案例表字段列表

			return $ar;
		}

		/* 法律案例表字段列表
		 *
		 *
		 *
		 *
		 */
		public function lawCaseTableFieldList ($b_enable_field_name=false)
		{
			$this->m_cHelper->gfDbQuery()->select ("show full fields from ".$this->m_cHelper->gfGetTableNameByConstKey('ME_LAW_CASE'))->forEachRow 
			(
				function ($row) use($b_enable_field_name)
				{
					if ( in_array($row->Field,[
                        'law_case_id',
                        'status',
                        'owner_id',
                        'created_at',
                        'updated_at',
                        'client_id',
                        'start_mediator_time',
                        'law_case_custom',
                        'seal_file_ids',
                        'main_respondent_phone_id',
                        'is_send_law_latter',
                        'is_send_latter',
                        'law_case_batch_number',
                        'law_case_status',
                        'law_case_code',
                        'mediator_id',
                        'seats_id',
                    ],true) /* exclude some fields */)
					{
						return null;
					}
					else
					{
						$arx	=	[
										'field'										=> $b_enable_field_name?$row->Field:''	,					# 数据库字段名字
										'field_md5'									=> md5($row->Field)						,					# 数据库字段名字直接做md5哈希
										'comment'									=> $row->Comment						,
										'type'										=> $row->Type							,
									];
						if ($b_enable_field_name){}else{unset($arx['field']);}
						return $arx;
					}
				}
				,
				$ar
			);

			return	[
							'law_case_table_field_list'								=> $this->m_cHelper->toObject($ar)->content
					];
		}
	}
